package com.jph.simple;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import adapter.NewGroupFriendAdapter;
import common.SystemUtil;
import container.FriendManager;
import container.PlayerContainer;
import model.Friend;
import socket.ServerSession;
import utgame.UtMessage.GroupInfo;
import utgame.UtMessage.MS_CreateGroup;
import utgame.UtMessage.MessagePacket.MessageType;
import utgame.UtMessage.MC_CreateGroup;



public class NewGroupActivity extends TitleActivity{

    public static final String TAG = "NewGroupActivity";

    private ListView mLvFriends;

    private List<Friend> mFriendList = new ArrayList<>();

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MessageType.CreateGroup_VALUE:
                    MS_CreateGroup msCreateGroup = null;
                    try {
                        msCreateGroup = MS_CreateGroup.parseFrom((byte[]) msg.obj);
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    if (msCreateGroup == null || msCreateGroup.getErrorCode() != 0) return;

                    GroupInfo groupInfo = msCreateGroup.getGroup();

                    if (groupInfo.getCreatorName().equals(PlayerContainer.getInstance().getName())){

                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString(PlayerChatActivity.ParamName, groupInfo.getName());
                        bundle.putInt(PlayerChatActivity.ParamType, PlayerChatActivity.ChatTypeGroup);

                        intent.setClass(NewGroupActivity.this, GroupChatActivity.class);
                        intent.putExtras(bundle);

                        startActivity(intent);

                        finish();

                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_group);

        mLvFriends = (ListView)findViewById(R.id.lv_friends);

        updateFriendList();

        ServerSession.getInstance().addHandler(TAG, mHandler);

        setTitle("发起群聊");
        showBackwardView(R.string.back, true);
        showForwardView(R.string.sure, R.drawable.sure_bkg, true);


        NewGroupFriendAdapter newGroupFriendAdapter = new NewGroupFriendAdapter(this,
                R.layout.new_group_item, mFriendList);          //关联数据和子布局
        mLvFriends.setAdapter(newGroupFriendAdapter);                   //绑定数据和适配器
        mLvFriends.setOnItemClickListener(new AdapterView.OnItemClickListener() {  //点击每一行的点击事件

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position,
                                    long id) {
                Friend friend = mFriendList.get(position);
                friend.setSelect(!friend.isSelect());
                ((NewGroupFriendAdapter)(mLvFriends.getAdapter())).notifyDataSetChanged();
            }
        });
    }

    protected void onBackward(View backwardView){
        backToMainActivity();
    }

    protected void onForward(View forwardView) {

        String selfName = PlayerContainer.getInstance().getName();

        MC_CreateGroup.Builder builder = MC_CreateGroup.newBuilder();
        builder.setGroupName(selfName + "_" + SystemUtil.getLocaltime());
        builder.setCreatorName(selfName);

        for (Friend friend : mFriendList){
            if (friend.isSelect()){
                builder.addMemberName(friend.getName());
            }
        }

        ServerSession.getInstance().sendMessage(MessageType.CreateGroup, builder.build().toByteString());
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        backToMainActivity();
    }

    private void backToMainActivity(){
        startActivity(new Intent(this, MainActivity.class));
        finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    private void updateFriendList(){

        mFriendList.clear();

        mFriendList.addAll(FriendManager.getInstance().getFriendList());
        Collections.sort(mFriendList, new SortFriendByOnline());

//        mFriendList.add(0, new Friend(Friend.imageIds[0], getResources().getString(R.string.group_chat), true));

    }
}
